package com.jxy.pay.service.impl;

import com.jxy.pay.composite.DeptItem;
import com.jxy.pay.mock.DeptDataMock;
import com.jxy.pay.service.IDeptService;
import com.jxy.pay.visitor.DeptNameVisitor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName DeptServiceImpl
 * @Description TODO
 * @Author zheng
 * @Date 2022/10/20 20:50
 * @Version 1.0
 **/
@Service
public class DeptServiceImpl implements IDeptService {
    @Override
    public DeptItem list() {
        return DeptDataMock.rootItem;
    }

    @Override
    public DeptItem add(DeptItem deptItem) {
        DeptItem rootItem = DeptDataMock.rootItem;
        this.addItem(rootItem, deptItem);
        return deptItem;
    }

    @Override
    public DeptItem del(int id) {
        return null;
    }

    @Override
    public void print() {
        DeptNameVisitor deptNameVisitor = new DeptNameVisitor();
        deptNameVisitor.visitor(DeptDataMock.rootItem);
    }

    private void addItem(DeptItem rootItem, DeptItem item) {
        //在当前节点下加子节点
        if (item.getPid() == rootItem.getId()) {
            rootItem.add(item);
        } else {
            List<DeptItem> children = rootItem.getChildren();
            for (DeptItem child : children) {
                if (item.getPid() == child.getId()) {
                    child.add(item);
                    break;
                } else {
                    addItem(child, item);
                }
            }
        }
    }


}
